import Vue from 'vue'
//#ifdef H5
import map from '../Map'
//#endif
import {Storage} from '../Storage/index'

const AuthorizeList = {
    'scope.userInfo': {
        methods: ['getUserInfo'],
        msg: '获取用户信息授权失败'
    },
    'scope.userLocation': {
        methods: ['getLocation', 'chooseLocation'],
        msg: '获取用户信息授权失败'
    },
    'scope.userLocationBackground': {
        methods: ['userLocationBackground']
    },
    'scope.address': {
        methods: ['chooseAddress']
    },
    'scope.record': {
        methods: ['getRecorderManager']
    },
    'scope.writePhotosAlbum': {
        methods: ['saveImageToPhotosAlbum', 'saveVideoToPhotosAlbum']
    },
    'scope.camera': {},
    'scope.invoice': {
        methods: ['chooseInvoice']
    },
    'scope.invoiceTitle': {
        methods: ['chooseInvoiceTitle']
    },
    'scope.werun': {
        methods: ['getWeRunData']
    },
};


export default class Authorize {
    constructor(wx_jssdk) {
        this.localAuthSetting = {};
        this.getSetting();
        this.wx_jssdk = wx_jssdk
    }

    set authSetting(obj) {
        this.localAuthSetting = {...obj};
        Storage.setStorageSync('__authSetting__', this.localAuthSetting)
    }

    get authSetting() {
        const AuthSetting = this.localAuthSetting;
        const localAuthSetting = Storage.getStorageSync('__authSetting__')
        return this.localAuthSetting = {
            ...AuthSetting,
            ...localAuthSetting,
        }
    }

    getSetting() {
        let vm = this;
        return new Promise(resolve => {
            const authSetting = {};
            // #ifndef H5
            Object.keys(AuthorizeList).forEach(v => authSetting[v] = null);
            uni.getSetting({
                complete(res) {
                    vm.authSetting = {
                        ...authSetting,
                        ...res.authSetting
                    };
                    resolve();
                }
            });
            // #endif
            // #ifdef H5
            Object.keys(AuthorizeList).forEach(v => authSetting[v] = true);
            vm.authSetting = {...authSetting};
            resolve();
            // #endif
        })
    }

    AppLaunch() {
        // 'scope.userLocation'
        // #ifdef H5
        return Promise.resolve();
        // #endif
        // #ifndef H5
        return this.authorize(['scope.userInfo'])
        // #endif
    }

    openSetting(scope) {
        let vm = this;
        if (typeof scope !== "string") return Promise.reject();
        return new Promise((resolve, reject) => {
            const authSetting = {};
            // #ifndef H5
            (function fun({tapIndex} = {}) {
                let flag = true;
                if (tapIndex && typeof tapIndex == "number" && tapIndex !== 0) flag = false;
                flag && uni.openSetting({
                    complete(res) {
                        if ("openSetting:fail can only be invoked by user TAP gesture." === res.errMsg) {
                            return wx.showActionSheet({
                                itemList: ['去授权'],
                                success: fun,
                                fail(res) {
                                    console.log(res.errMsg)
                                    resolve({status: false, errMsg: res.errMsg})
                                }
                            })
                        }
                        console.log(res);
                        const authSetting = {};
                        Object.keys(AuthorizeList).forEach(v => authSetting[v] = null);
                        vm.authSetting = {...authSetting, ...res.authSetting};
                        if (res.authSetting && res.authSetting[scope] === true) {
                            resolve({status: true, errMsg: res.errMsg});
                        } else {
                            resolve({status: false, errMsg: res.errMsg})
                        }
                    }
                });
            })()

            // #endif
            // #ifdef H5
            resolve({status: false});
            // #endif
        })
    }

    authorize(scope) {
        let keys = Object.keys(AuthorizeList);
        let vm = this;
        if (!scope && !uni.authorize) return Promise.reject();
        let scopes = [];
        if (typeof scope === "string") scopes.push(scope);
        if (Array.isArray(scope) && scope.length > 0) {
            scopes = [...scope]
        }
        scopes = keys.filter(v => scopes.indexOf(v) > -1);
        if (!Array.isArray(scopes) || scopes.length === 0) return Promise.reject();
        const P = scopes.map(scope => {
            return new Promise((resolve, reject) => {
                uni.authorize({
                    scope,
                    complete(result) {
                        resolve(result)
                    }
                })
            })
        });
        return new Promise(resolve => {
            Promise.all(P).finally(async res => {
                await vm.getSetting();
                const acths = vm.authSetting;
                const _scopes = keys.filter(v => acths[v] === true);
                let txt = `授权成功${_scopes.length}个(${_scopes.join(',')})`;
                if (scopes.length - _scopes.length > 0) {
                    txt += `，失败${scopes.length - _scopes.length}个`
                }
                resolve({
                    msg: txt,
                    status: (scopes.length - _scopes.length) === 0,
                    authSetting: acths,
                    info: res
                })
            })
        })
    }

    /**
     * 获取当前定位
     * @param type
     * @param altitude
     * @param geocode
     * @return {Promise<unknown>}
     */
    getLocation({type = 'gcj02', altitude = false, geocode = false} = {}) {
        return new Promise(resolve => {
            // #ifdef H5
            map.getLocation().finally(res => {
                // console.log(res);
                resolve(res)
                // errMsg: "getLocation:fail"
            });
            // #endif
            // #ifndef H5
            uni.getLocation({
                type,
                altitude,
                geocode,
                // fail (error) {
                //     resolve(error)
                // },
                // success (result) {
                //     resolve(result)
                // },
                complete(result) {
                    resolve(result)
                }
            })
            // #endif
        })
    }

    /**
     * 获取用户授权
     * @return {Promise<unknown>}
     */
    getUserInfo(bol = true) {
        let vm = this;
        return new Promise((resolve, reject) => {
            // const cur = vm.getCurrentPage();
            uni.getUserInfo({
                withCredentials: true,
                async complete(result) {
                    result.status = /getUserInfo:ok/.test(result.errMsg);
                    resolve(result)
                }
            })
        })
    }

    getCurrentPage() {
        if (Vue.$global_util) {
            return Vue.$global_util.getCurrentPage(...arguments)
        } else {
            return {}
        }
    }

    saveImageToPhotosAlbum({filePath}) {
        let vm = this;
        return new Promise(async resolve => {
            let num = 0;
            (function fun(flag) {
                if (num >= 1) return resolve({errMsg: "授权失败"})
                vm.openSettingFun('scope.writePhotosAlbum', flag).finally(result => {
                    if (result.isOpenSetting) num++;
                    if (result.status === true)
                        uni.saveImageToPhotosAlbum({
                            filePath,
                            success: resolve,
                            async fail(err) {
                                if (vm.isAuthDeny(err.errMsg)) {
                                    fun(false);
                                } else {
                                    resolve(err)
                                }
                            }
                        })
                    else throw "授权失败"
                }).catch(err => {
                    resolve({errMsg: "授权失败"})
                })
            })()
            // fun();
        })

    }

    async openSettingFun(scope, bol = true) {
        let vm = this;
        if (typeof scope !== "string") return Promise.reject();
        let isOpenSetting = false
        if (vm.authSetting[scope] === false || bol === false) {
            vm.authSetting[scope] = false;
            isOpenSetting = true;
            const result = await vm.openSetting(scope)
            if (result.status === false) return Promise.resolve({status: false, isOpenSetting})
        }
        return Promise.resolve({status: true, isOpenSetting})
    }

    isAuthDeny(errMsg) {
        if (typeof errMsg !== "string") return;
        return /fail\s?auth\s?deny/.test(errMsg)
    }

}
